import config from '@/config'
import token from '@/utils/token'
import { getCaptcha, remoteMacAddr } from '@/api/app'
const { homeName } = config

const app = {
  namespaced: true,
  state: {
    breadCrumbList: [],
    tagNavList: []
  },
  mutations: {
    setTagNavList(state, route) {
      let tagList = []
      if (list) {
        tagList = [...list]
      } else {
        let list = localStorage.tagNavList
        tagList = list ? JSON.parse(list) : []
      }
      if (tagList[0] && tagList[0].name !== homeName) tagList.shift()
      let homeTagIndex = tagList.findIndex(item => item.name === homeName)
      if (homeTagIndex > 0) {
        let homeTag = tagList.splice(homeTagIndex, 1)[0]
        tagList.unshift(homeTag)
      }
      state.tagList = tagList
      localStorage.tagNavList = JSON.stringify([...tagList])
    }
  },
  actions: {
    getCaptchaHandler({ commit }) {
      return new Promise(resolve => {
        getCaptcha().then(resp => {
          if (resp.meta.success) {
            token.set(resp.data[token.key])
          }
          resolve(resp)
        })
      })
    },
    remoteMacAddrHandler({ commit }) {
      return new Promise((resolve, reject) => {
        remoteMacAddr()
          .then(resp => {
            if (resp.meta.success) {
              commit('user/setMacAddr', resp.data, { root: true })
              resolve()
            } else {
              reject(resp.data)
            }
          })
          .catch(err => {
            reject(err)
          })
      })
    }
  }
}

export default app
